﻿using Authentication.Configuration;
using Authentication.Model.Model;
using Authentication.Model.ViewModel.Warranty;
using Authentication.Web.Service;
using Common.Util;
using Common.Contract;
using Common.Contract.Authentication;
using Common.Contract.Authentication.Record;
using Common.Contract.Authentication.Request;
using Common.Contract.Customer.Record;
using Common.Contract.Paging;
using Common.Contract.Warranty;
using Common.Contract.Warranty.Request;
using Common.Service;
using Common.Service.DataTables;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Mvc;
using System.Globalization;

namespace Authentication.Web.Controller
{
    public class WarrantyController : ControllerBase
    {
        #region Saleout Verify
        [Authorize]
        public ActionResult SaleOut_Verify()
        {
            OTP.Instant.Counter = ulong.Parse(DateTime.UtcNow.ToString(SystemConfiguration.CounterDateTimeFormat));
            SaleOutVerifyViewModel vm = new SaleOutVerifyViewModel { IsSupperAdmin = string.Equals(CurrentUser, SystemConfiguration.SUPPER_ADMIN, StringComparison.OrdinalIgnoreCase), OtpCounter = OTP.Instant.Counter, Otp = OTP.Instant.GetCurrentOTP() };
            return View(vm);
        }

        [HttpPost]
        [Authorize]
        public ActionResult SaleOutVerifyData(DataTablesPageRequest pageRequest, string counter, string otp, string region, string billto, string fromdate, string todate, string confirmflag, string verifyflag)
        {
            OTP.Instant.Counter = (ulong)counter.ToNumber();
            DateTime timeGet; bool validateOtp = false;
            if (DateTime.TryParseExact(counter, SystemConfiguration.CounterDateTimeFormat, null, DateTimeStyles.None, out timeGet))
            {
                TimeSpan timeCheck = DateTime.UtcNow - timeGet;
                if (timeCheck.TotalMinutes <= SystemConfiguration.OTPLiveTimeMinute) validateOtp = true;
            }

            if (!validateOtp || OTP.Instant.GetCurrentOTP() != otp)
            {
                return Json(new DataTableResponse
                {
                    sEcho = pageRequest.Echo,
                    iTotalRecords = 0,
                    sColumns = pageRequest.ColumnNames,
                    aaData = new List<object[]> { }
                });
            }

            DataTableResponse pageResponse = null;
            using (ServiceClient<IWarranty> serviceClient = new ServiceClient<IWarranty>())
            {
                SearchSaleOutVerificationRequest request = new SearchSaleOutVerificationRequest
                {
                    Header = new RequestHeaderRecord
                    {
                        ApplicationKey = SystemConfiguration.ApplicationKey,
                        CallerName = "Authentication.Web.Controller.SystemController.ShopInfoData"
                    },
                    Page = new PageRecord
                    {
                        PageSize = pageRequest.DisplayLength,
                        PageIndex = pageRequest.DisplayLength > 0 ? pageRequest.DisplayStart / pageRequest.DisplayLength : 0
                    },
                    TextSearch = pageRequest.Search,
                    RegionIdentifier = region,
                    BillTo = billto,
                    StartDate = fromdate.ToDateTime(),
                    EndDate = todate.ToDateTime(),
                    ConfirmFlag = confirmflag.ToBoolean(),
                    VerifyFlag = verifyflag.ToBoolean()
                };
                var shopInfoRecords = serviceClient.Proxy.SearchSaleOutVerification(request);
                var resultShopInfo = (shopInfoRecords == null || shopInfoRecords.Records == null) ? new List<SaleOutVerificationRecord>() : shopInfoRecords.Records;
                pageResponse = new DataTableResponse
                {
                    sEcho = pageRequest.Echo,
                    iTotalRecords = shopInfoRecords.Page.TotalRecords,
                    sColumns = pageRequest.ColumnNames,
                    aaData = resultShopInfo.Select((x) =>
                    {
                        bool isNullShop = (x.ShopInfo == null);
                        return new object[]
                        {
                            x.Model,
                            x.SeriaNumber,
                            isNullShop? string.Empty: x.ShopInfo.ShopCode,
                            isNullShop? string.Empty: x.ShopInfo.ShopName??string.Empty,
                            isNullShop? string.Empty: (x.ShopInfo.Region==null||x.ShopInfo.Region.RegionIdentifier.IsNullOrWhiteSpace())?string.Empty:  x.ShopInfo.Region.RegionName,
                            isNullShop? string.Empty: x.ShopInfo.Channel??string.Empty,
                            isNullShop? string.Empty: x.ShopInfo.ShopType??string.Empty,
                            isNullShop? string.Empty: x.ShopInfo.BillToCode??string.Empty,
                            isNullShop? string.Empty: x.BillName??string.Empty,
                            isNullShop? string.Empty: x.ShopInfo.OwnerName??string.Empty,
                            isNullShop? string.Empty: x.ShopInfo.OwnerEmail??string.Empty,
                            isNullShop? string.Empty: (x.ShopInfo.Province==null||x.ShopInfo.Province.Identifier.IsNullOrWhiteSpace())?string.Empty:x.ShopInfo.Province.Identifier,
                            isNullShop? string.Empty: (x.ShopInfo.Province==null||x.ShopInfo.Province.Identifier.IsNullOrWhiteSpace())?string.Empty:x.ShopInfo.Province.ProvinceName, 
                            isNullShop? string.Empty: (x.ShopInfo.District==null||x.ShopInfo.District.DistrictIdentifier.IsNullOrWhiteSpace())?string.Empty:x.ShopInfo.District.DistrictIdentifier,
                            isNullShop? string.Empty: (x.ShopInfo.District==null||x.ShopInfo.District.DistrictIdentifier.IsNullOrWhiteSpace())?string.Empty:x.ShopInfo.District.DistrictName,
                            isNullShop? string.Empty: x.ShopInfo.Address??string.Empty,
                            isNullShop? string.Empty: x.ShopInfo.CellNo1??string.Empty,
                            isNullShop? string.Empty: x.ShopInfo.CellNo2??string.Empty,
                            x.EdiNumber??string.Empty,
                            x.Suffix??string.Empty,
                            x.SaleInDate.HasValue? x.SaleInDate.Value.ToString(SystemConfiguration.DateTimeFormat):string.Empty,
                            x.SaleOutDate.HasValue? x.SaleOutDate.Value.ToString(SystemConfiguration.DateTimeFormat):string.Empty,
                            x.UserCell??string.Empty,
                            x.VerifyFlag??false,
                            x.UserVerify??string.Empty,
                            x.ConfirmFlag??false,
                            x.ConfirmUser??string.Empty,
                            x.ConfirmComment??string.Empty,                                                            
                        };
                    }).ToList()
                };
            }
            return Json(pageResponse);
        }

        [Authorize]
        [HttpPost]
        public ActionResult Confirm_Saleout(SaleOutVerifyViewModel vm)
        {
            OTP.Instant.Counter = vm.OtpCounter;
            DateTime timeGet; bool validateOtp = false;
            if (DateTime.TryParseExact(vm.OtpCounter.ToString(), SystemConfiguration.CounterDateTimeFormat, null, DateTimeStyles.None, out timeGet))
            {
                TimeSpan timeCheck = DateTime.UtcNow - timeGet;
                if (timeCheck.TotalMinutes <= SystemConfiguration.OTPLiveTimeMinute) validateOtp = true;
            }

            if (!validateOtp || OTP.Instant.GetCurrentOTP() != vm.Otp)
            {
                ResponseRecord res = new ResponseRecord
                {
                    IsSuccess = false,
                    ErrorMessage = "Invalidate OTP check request"
                };
                return Json(res);
            }

            if (vm.SerialNumber.IsNullOrWhiteSpace() || vm.Model.IsNullOrWhiteSpace())
            {
                ResponseRecord res2 = new ResponseRecord
                {
                    IsSuccess = false,
                    ErrorMessage = "Invalidate SerialNumber/Model request - request null"
                };
                return Json(res2);
            }

            var header = new RequestHeaderRecord
            {
                ApplicationKey = SystemConfiguration.ApplicationKey,
                CallerName = "Authentication.Web.Controller.WarrantyController.Confirm_Saleout",
                UserRequest = CurrentUser
            };

            using (ServiceClient<IWarranty> serviceClient = new ServiceClient<IWarranty>())
            {
                ConfirmSaleOutRequest confirmRequest = new ConfirmSaleOutRequest
                {
                    Header = header,
                    Record = new SaleOutVerificationRecord
                    {
                        BillCode = vm.BillToCode,
                        BillName = vm.BillToName,
                        ConfirmComment = vm.ConfirmComment,
                        ConfirmUser = CurrentUser,
                        EdiNumber = vm.EDINumber,
                        ShopInfo = new ShopInfoRecord
                        {
                            ShopCode = vm.ShopCode,
                            ShopName = vm.ShopName,
                            CellNo1 = vm.ShopCell
                        },
                        Suffix = vm.Suffix,
                        Model = vm.Model,
                        SeriaNumber = vm.SerialNumber,
                        SaleInDate = vm.SellinDate.ToDateTime(),
                        SaleOutDate = vm.SelloutDate.ToDateTime(),
                        UserCell = vm.UserCell
                    }
                };
                var response = serviceClient.Proxy.ConfirmSaleOut(confirmRequest);
                return Json(response);
            }
        }
        #endregion


        #region Period Inquiry
        public ActionResult Period_Inquiry()
        {
            return View();
        }

        [HttpPost]
        [Authorize]
        public ActionResult PeriodInquiryData(DataTablesPageRequest pageRequest, string serial, string model)
        {
            DataTableResponse pageResponse = null;
            using (ServiceClient<IWarranty> serviceClient = new ServiceClient<IWarranty>())
            {
                SearchPeriodInquiryRequest request = new SearchPeriodInquiryRequest
                {
                    Header = new RequestHeaderRecord
                    {
                        ApplicationKey = SystemConfiguration.ApplicationKey,
                        CallerName = "Authentication.Web.Controller.SystemController.PeriodInquiryData"
                    },
                    Page = new PageRecord
                    {
                        PageSize = pageRequest.DisplayLength,
                        PageIndex = pageRequest.DisplayLength > 0 ? pageRequest.DisplayStart / pageRequest.DisplayLength : 0
                    },
                    TextSearch = pageRequest.Search,
                    Model = model,
                    SerialNumber = serial
                };
                var shopInfoRecords = serviceClient.Proxy.SearchPeriodInquiry(request);
                var resultShopInfo = (shopInfoRecords == null || shopInfoRecords.Records == null) ? new List<PeriodInquiryRecord>() : shopInfoRecords.Records;
                pageResponse = new DataTableResponse
                {
                    sEcho = pageRequest.Echo,
                    iTotalRecords = shopInfoRecords.Page.TotalRecords,
                    sColumns = pageRequest.ColumnNames,
                    aaData = resultShopInfo.Select(x => new object[]{ 
                                                             x.SerialNumber,
                                                             x.Model,
                                                             x.Product,
                                                             x.Suffix??string.Empty, 
                                                             x.EndUserCell??string.Empty, 
                                                             x.RequestDate.HasValue? x.RequestDate.Value.ToString(SystemConfiguration.DateTimeFormat):string.Empty,
                                                             x.StartDate.HasValue? x.StartDate.Value.ToString(SystemConfiguration.DateTimeFormat):string.Empty,
                                                             x.EndDate.HasValue? x.EndDate.Value.ToString(SystemConfiguration.DateTimeFormat):string.Empty,
                                                             x.RemainDay, 
                                                             x.ShopCell??string.Empty                                                    
                    }).ToList()
                };
            }
            return Json(pageResponse);
        }
        #endregion


        #region Serial Chasing
        public ActionResult Serial_Chasing()
        {
            return View();
        }

        [HttpPost]
        [Authorize]
        public ActionResult SerialChasingData(DataTablesPageRequest pageRequest, string serial, string model)
        {
            DataTableResponse pageResponse = null;
            using (ServiceClient<IWarranty> serviceClient = new ServiceClient<IWarranty>())
            {
                SearchSerialChasingRequest request = new SearchSerialChasingRequest
                {
                    Header = new RequestHeaderRecord
                    {
                        ApplicationKey = SystemConfiguration.ApplicationKey,
                        CallerName = "Authentication.Web.Controller.SystemController.SerialChasingData"
                    },
                    Page = new PageRecord
                    {
                        PageSize = pageRequest.DisplayLength,
                        PageIndex = pageRequest.DisplayLength > 0 ? pageRequest.DisplayStart / pageRequest.DisplayLength : 0
                    },
                    TextSearch = pageRequest.Search,
                    Model = model,
                    SerialNumber = serial
                };
                var shopInfoRecords = serviceClient.Proxy.SearchSerialChasing(request);
                var resultShopInfo = (shopInfoRecords == null || shopInfoRecords.Records == null) ? new List<SerialChasingRecord>() : shopInfoRecords.Records;
                pageResponse = new DataTableResponse
                {
                    sEcho = pageRequest.Echo,
                    iTotalRecords = shopInfoRecords.Page.TotalRecords,
                    sColumns = pageRequest.ColumnNames,
                    aaData = resultShopInfo.Select(x => new object[]{ 
                                                             x.SerialNumber,
                                                             x.BoxNo,
                                                             x.ProductModel??string.Empty, 
                                                             x.ProductSuffix??string.Empty, 
                                                             x.ProductDate.HasValue? x.ProductDate.Value.ToString(SystemConfiguration.DateTimeFormat) :string.Empty, 
                                                             x.OrderNumber??string.Empty,
                                                             x.SaleModel??string.Empty, 
                                                             x.SaleSuffix??string.Empty, 
                                                             x.SellinDate.HasValue? x.SellinDate.Value.ToString(SystemConfiguration.DateTimeFormat) :string.Empty, 
                    }).ToList()
                };
            }
            return Json(pageResponse);
        }
        #endregion
    }
}